﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Sunboxsoft.WinForm;
using WebRef = Sunboxsoft.ASMS.Client.Domain.WebRef;
using Service = Sunboxsoft.ASMS.Client.Domain.Service;
using Sunboxsoft.Common;
using Sunboxsoft.ASMS.Client.UI.Properties;
using Sunboxsoft.ASMS.Client.Domain;


namespace Sunboxsoft.ASMS.Client.UI.Pickers
{
    /// <summary>
    /// 选择预约单
    /// </summary>
    public partial class BookingBillPicker : UserControl, IView
    {
        #region fields
        private int _pageIndex;
        private int _pageCount;
        Promise _promise = new Promise();
        #endregion

        private IntCodeTextItem[] _availableStatusArray;

        public BookingBillPicker()
        {
            _availableStatusArray = Constant.BookingBillStatus.Enumerate();
            InitializeComponent();

            ctlDateBegin.DateTime = DateTime.Now;
            ctlDateEnd.DateTime = DateTime.Now.AddMonths(1);

            ctlLookupStatus.Properties.DisplayMember = "Text";
            ctlLookupStatus.Properties.DataSource = _availableStatusArray;
            ctlLookupStatus.ItemIndex = 0;
        }

        public BookingBillPicker(IntCodeTextItem[] availableStatusArray, bool isControlTime)
        {
            _availableStatusArray = availableStatusArray;
            InitializeComponent();

            if (isControlTime)
            {
                ctlDateBegin.DateTime = DateTime.Now;
                ctlDateEnd.DateTime = DateTime.Now.AddMonths(1);
            }
            ctlLookupStatus.Properties.DisplayMember = "Text";
            ctlLookupStatus.Properties.DataSource = _availableStatusArray;
            ctlLookupStatus.EditValue = _availableStatusArray[0];
        }
        /// <summary>
        /// 指定了特定的时间和类型，时间不能选择
        /// </summary>
        /// <param name="beginTime"></param>
        /// <param name="endTime"></param>
        /// <param name="availableStatusArray"></param>
        public BookingBillPicker(DateTime beginTime, DateTime endTime, IntCodeTextItem[] availableStatusArray)
        {
            _availableStatusArray = availableStatusArray;
            InitializeComponent();

            ctlDateBegin.DateTime = beginTime.Date;
            ctlDateEnd.DateTime = endTime.Date;
            ctlDateBegin.Enabled = false;
            ctlDateEnd.Enabled = false;

            ctlLookupStatus.Properties.DisplayMember = "Text";
            ctlLookupStatus.Properties.DataSource = _availableStatusArray;
            ctlLookupStatus.EditValue = _availableStatusArray[0];
        }

        #region IView 成员

        public void RegisterAction(ActionNodeCollection collection)
        {
            collection.AddAction(new ActionNode("ok", Resources.isOK, "确定", OnOKActionClick))
                .AddAction(new ActionNode("refresh", Resources.isRefresh, "刷新", OnRefreshActionClick))
                .AddAction(new ActionNode("cancel", Resources.isDelete, "取消", OnCancelActionClick));
        }
        public void Active(ViewActiveArgs args)
        {
            _promise.Then(LoadBookingBillPagedData).Run();
        }
        public void Resume(ViewResumeArgs args)
        {
        }
        public ViewHeader GetHeader()
        {
            return new ViewHeader("选择预约单");
        }
        #endregion

        #region actions
        private void OnOKActionClick(object sender, object e)
        {
            WebRef.VBookingBill bill = ctlGridView.GetRow(ctlGridView.FocusedRowHandle) as WebRef.VBookingBill;
            if (bill == null)
            {
                return;
            }
            UIContext.Current.ViewManager.CloseView(true, bill);
        }

        private void OnCancelActionClick(object sender, object e)
        {
            UIContext.Current.ViewManager.CloseView(false, null);
        }
        private void OnRefreshActionClick(object sender, object e)
        {
            LoadBookingBillPagedData();
        }
        /// <summary>
        /// 双击行选中事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ctlGridView_MouseDown(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left && e.Clicks == 2)
            {
                DevExpress.XtraGrid.Views.Grid.ViewInfo.GridHitInfo hInfo = ctlGridView.CalcHitInfo(new Point(e.X, e.Y));
                if (hInfo.InRow)
                {
                    if (ctlGridView.FocusedRowHandle > -1)
                    {
                        WebRef.VBookingBill vBookingBill = ctlGridView.GetFocusedRow() as WebRef.VBookingBill;
                        UIContext.Current.ViewManager.CloseView(true, vBookingBill);
                    }
                }
            }
        }
        #endregion

        #region methods

        private void LoadBookingBillPagedData()
        {
            DateTime? beginTime = null;
            DateTime? endTime = null;
            if (!GetDataRange(out beginTime, out endTime))
            {
                UIContext.Current.ViewManager.ShowWarning("请选择正确的日期范围!");
            }

            this.ShowMask("loading...");
            UIContext.Current.InvokeAsync(() =>
            {
                PagedResult<WebRef.VBookingBill> result = new Service.QueryService().QueryBookingBillPagedList(ModuleContext.Current.BusinessId.Value,
                    ModuleContext.Current.StationId.Value,
                    beginTime,
                    endTime,
                    null,
                    GetStatus(),
                    _pageIndex * GetPageLimit(), GetPageLimit());
                this.BeginInvoke(new Action<PagedResult<WebRef.VBookingBill>>((p) =>
                {
                    if (p.IsSuccess)
                    {
                        ctlGrid.Paginate<WebRef.VBookingBill>(p, out _pageIndex, out _pageCount);
                    }
                    else
                    {
                        MessageBox.Show(result.Message);
                    }
                    this.HideMask();
                }), result);
            });
        }

        private int GetPageLimit()
        {
            return 15;
        }

        private bool GetDataRange(out DateTime? beginTime, out DateTime? endTime)
        {
            if (!string.IsNullOrEmpty(this.ctlDateBegin.Text))
            {
                beginTime = Convert.ToDateTime(this.ctlDateBegin.Text);
            }
            else
            {
                beginTime = null;
            }
            if (!string.IsNullOrEmpty(this.ctlDateEnd.Text))
            {
                endTime = Convert.ToDateTime(this.ctlDateEnd.Text);
            }
            else
            {
                endTime = null;
            }

            if (beginTime != null && endTime != null)
            {
                if (beginTime > endTime)
                {
                    return false;
                }
            }
            return true;
        }

        public int GetStatus()
        {
            Domain.IntCodeTextItem item = ctlLookupStatus.GetSelectedDataRow() as Domain.IntCodeTextItem;
            if (item == null)
            {
                return Domain.Constant.BookingBillStatus.All;
            }
            return item.Code;
        }
        #endregion


    }
}
